package com.kooison.idevice4u;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kooison.idevice4u.bean.DocContent;
import com.kooison.idevice4u.bean.ProductDetail;
import com.kooison.idevice4u.crawler.AppleStoreCrawler;
import com.kooison.idevice4u.database.EmailLog;
import com.kooison.idevice4u.database.EmailLogService;
import com.kooison.idevice4u.email.GAEMail;

@SuppressWarnings("serial")
public class SearchProductServlet extends HttpServlet {
	private final Logger logger = Logger.getLogger(this.getClass().getName());
	private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	private static String[] mailingList = new String[] { "wilsonwong@wisers.com", "kooison@gmail.com",
			"maple.csf@gmail.com", "dootcoco@gmail.com", "zita.lo@gmail.com", "chriswong008@yahoo.com.hk",
			"bryanhk@gmail.com", "sandyleung111@yahoo.com.hk", "henry032683@gmail.com", "cokei519@gmail.com",
			"cokei519@yahoo.com.hk", "hello_doldol@hotmail.com", "jennifer8803@hotmail.com", "faichai222@yahoo.com.hk",
			"leowongwk@yahoo.com.hk", "gordon.wang.pb@gmail.com", "leoyin2003@yahoo.com.hk", "sammyleung2000@hotmail.com",
			"catherinechunghc@yahoo.com.hk", "ritacheung1012@hotmail.com", "alfred.h.ling@jpmorgan.com", "fionkwan@gmail.com"};
	
	// private static String[] mailingList = new String[] { "kooison@gmail.com" };
	// private static String[] mailingList = new String[] { };

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		try {
			logger.info("Local time: " + getLocalDate(new Date()));

			// Check param
			String product = req.getParameter("product");
			if (product == null) {
				product = getServletConfig().getInitParameter("product");
			}
			String region = req.getParameter("region");
			if (region == null) {
				region = getServletConfig().getInitParameter("region");
			}

			// insert new email user
			EmailLogService els = new EmailLogService();
			initUsers(els, product, region);

			AppleStoreCrawler crawler = new AppleStoreCrawler(product, region);
			ArrayList<ProductDetail> list = (ArrayList<ProductDetail>) crawler.getResultList();
			String content = DocContent.CreateContent(list);
			String title = DocContent.CreateTitle(list);

			resp.setContentType("text/html");
			resp.getWriter().println(content);

			EmailLog.STATUS status = null;
			if (crawler.isAvailable()) {
				status = EmailLog.STATUS.AVAILABLE;
				logger.info(product + "@" + region + " is available ^_^");
			} else {
				status = EmailLog.STATUS.NOT_AVAILABLE;
				logger.info(product + "@" + region + " is not available :(");
			}

			
			logger.info("go email section...");
			ArrayList<String> bccList = new ArrayList<String>();
			List<EmailLog> allMailingList = els.retrieve(product, region);
			logger.info("no. of email selected: " + allMailingList.size());
			for (EmailLog log : allMailingList) {
				// logger.info("selected email: " + log.getEmail());
				if (isNeedToSendEmail(log, status)) {
					bccList.add(log.getEmail());
					saveLog(els, log.getEmail(), product, region, status);
				}
			}
			
			if (bccList.size() > 0) {
				// Send mail
				GAEMail mail = new GAEMail();
				mail.setFromAddress("kooison@gmail.com");
				mail.setMsgBody(content);
				mail.setSubject(title);
				// mail.setToAddress(new String[] { log.getEmail() });
				mail.setBccAddress(bccList.toArray(new String[0]));
				mail.send();
				// saveLog(els, log.getEmail(), product, region, status);
			}
			
			logger.info("done...");
			
		} catch (Exception e) {
			logger.log(Level.WARNING, e.getMessage());
			e.printStackTrace();
			resp.setContentType("text/html");
			resp.getWriter().println(e);
		}
	}

	private void saveLog(EmailLogService els, String email, String product, String region, EmailLog.STATUS status) {
		int count = 1;
		List<EmailLog> results = els.retrieve(email, product, region);
		for (EmailLog el : results) {
			count = el.getSentMailCount() + 1;
			el.setSentMailCount(count);
			el.setLastModified(sdf.format(new Date()));
			el.setProductStatus(status.toString());
			els.update(el);
		}
	}
	
	private boolean isNeedToSendEmail(EmailLog el, EmailLog.STATUS status) {
		if (el.isEnabled()) {
			if (el.getProductStatus() == null || !el.getProductStatus().equals(status.toString())) {
				logger.info("Notification sent to " + el.getEmail());
				return true;
			}
		}
		// logger.info("No notification sent to " + el.getEmail());
		return false;
	}
	
	private synchronized void initUsers(EmailLogService els, String product, String region) {
		for (String email : mailingList) {
			List<EmailLog> results = els.retrieve(email, product, region);
			if (results.isEmpty()) {
				EmailLog el = new EmailLog(email, email, product, region, sdf.format(new Date()), EmailLog.STATUS.NOT_AVAILABLE);
				els.create(el);
				logger.info("New user creaded: " + el.toString());
			}
		}
	}

	private String getLocalDate(Date date) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8")); // all date object is display in GMT+8 time zone
		return dateFormat.format(date);
	}
}
